using Lemon.BackgroundJobs.Abstractions;
using Lemon.BackgroundJobs.Abstractions.PublishSubscribe;
using Microsoft.Extensions.DependencyInjection;

namespace Lemon.BackgroundJobs.RabbitMQ.PublishSubscribe;

public abstract class PublishSubscribeJob<T> : IPublishSubscribeJob<T> where T : class, new()
{
    private readonly string _exchange;
    private readonly IPublishSubscribe? _publishSubscribe;

    protected PublishSubscribeJob(IServiceCollection serviceCollection, string exchange)
    {
        _exchange = exchange;
        _publishSubscribe = serviceCollection.BuildServiceProvider().GetService<IPublishSubscribe>();
    }

    protected abstract void Execute(T args);
    
    public void Receive()
    {
        if (_publishSubscribe != null)
        {
            _publishSubscribe.Subscribe<T>(_exchange, this.Execute);
        }
    }
}